package com.cdtu.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdtu.entity.*;
import com.cdtu.service.*;
import com.cdtu.util.RedisConst;
import com.cdtu.util.SMSUtils;
import com.cdtu.vo.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.cdtu.controller.MessageController.CACHE_CERTIFY_KEY;

/**
 * @author : Sakura
 * @Date : 2023/1/13 14:59
 */
@Slf4j
@RestController
//解决跨域问题
@CrossOrigin
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CertifyTypeService typeService;

    @Autowired
    CertifyTypeService certifyTypeService;
    @Autowired
    private RUserSpecialityService rUserSpecialityService;

    @Autowired
    private SpecialityService specialityService;
    @Autowired
    SpecialityTypeService specialityTypeService;

    @Autowired
    private RUserTaskService rUserTaskService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RUserCertifyService rUserCertifyService;

    @Autowired
    private CertifyService certifyService;
    @Autowired
    private MessagesService messagesService;

    @Autowired
    StringRedisTemplate redisTemplate;


    @GetMapping("/findUsers/{page}/{pageSize}")
    public R getUsers(@PathVariable("page") Integer pageNow, @PathVariable("pageSize") Integer pageSize,
                      String grade, String certifyTypeId){

        Map<String, Object> map = userService.findByCategory(pageNow, pageSize, grade, certifyTypeId);
        return R.success(map);
    }


    @GetMapping("/detail/{id}")
    public R userDetail(@PathVariable("id") long id){
//        System.out.println(id);
        User user = userService.getById(id);
//        传到前端的是userVO
        List<Long> certifyIds = rUserCertifyService.findByUserId(id);
//        根据ids找出所有的证书名称
        List<String> certifyNames = certifyService.findByIds(certifyIds);
//        根据用户名获取技能特长属性
        List<Long> specIds = rUserSpecialityService.findByUserId(id);
        List<SpecialityVO> specialityVOList = specialityService.findByIds(specIds,id);
//        技能特长解决后就查找设计任务
        List<Long> taskIds = rUserTaskService.findByUserId(id);
        List<String> tasks = taskService.findByIds(taskIds);
//        接下来封装VO对象
        UserVO vo = new UserVO();
        vo.setId(user.getId());
        vo.setName(user.getName());
        vo.setEthnic(user.getEthnic());
        vo.setVocation(user.getVocation());
        vo.setPhone(user.getPhone());
        vo.setHomeAddress(user.getHomeAddress());
        vo.setComAddress(user.getComAddress());
        vo.setIdCard(user.getIdCard());
        vo.setSpeciality(specialityVOList);
        vo.setCertify(certifyNames);

        vo.setTasks(tasks);
        vo.setGrade(user.getGrade());
        vo.setWorkHour(user.getWorkHour());

        List<String> access= new ArrayList<>();
       if (user.getAccess()!=null){
           if (user.getAccess()==1){
               access.add("志愿者");
               vo.setAccess(access);
           }
           if(user.getAccess()==2){
               access.add("组长");
               vo.setAccess(access);
           }if(user.getAccess()==3){
               access.add("应急管理员");
               vo.setAccess(access);
           }
       }
        vo.setSex(user.getSex());
        vo.setAge(user.getAge());
        vo.setUsername(user.getUsername());
        vo.setCheckUser(user.getCheckUser());
        vo.setRegTime(user.getRegTime());
        vo.setUpdateTime(user.getUpdateTime());
        return R.success(vo);

    }

    @Transactional
    @DeleteMapping("/delete/{id}")
    public R deleteUser(@PathVariable("id") long id){

//        System.out.println(id);
        boolean result2 = rUserTaskService.removeByUid(id);

        boolean result3 = rUserSpecialityService.removeByUid(id);

        boolean result4 = rUserCertifyService.removeByUid(id);

        boolean result1 = userService.removeById(id);

        if (result1&&result2&&result3&&result4){
            return R.success("删除成功");
        }

        return R.error("删除失败，请稍后尝试");
    }

   /**
   * 获取所有特长类型列表
   * @author wp
   * @param
   * @date 2023/1/17 15:55
   * @return
   */
   @GetMapping("/specialTypeList")
   public  R getSpecialTypeList(){
      return R.success( specialityTypeService.list());
   }
    /**
     * 根据特长类型id 获取所有的子特长列表
     * @author wp
     * @param
     * @date 2023/1/17 15:29
     * @return
     */
    @GetMapping("/specialList/{id}")
    public R getSpecialList(@PathVariable("id") long id ){
        LambdaQueryWrapper<Speciality> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Speciality::getTypeId,id);
        return R.success(specialityService.list(queryWrapper));
    }
    /**
     * 获取所有证书类型列表
     * @author wp
     * @param
     * @date 2023/1/17 15:55
     * @return
     */
    @GetMapping("/certifyTypeList")
    public  R getCertifyTypeList(){
        return R.success( certifyTypeService.list());
    }
    /**
     * 根据特证书型id 获取所有的子证书列表
     * @author wp
     * @param
     * @date 2023/1/17 15:29
     * @return
     */
    @GetMapping("/certifyList/{id}")
    public R getCertifyList(@PathVariable("id") long id ){
        LambdaQueryWrapper<Certify> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Certify::getTypeId,id);
        return R.success(certifyService.list(queryWrapper));
    }

    @GetMapping("/UDetail/{id}")
    public R userDetailU(@PathVariable("id") long id){
        User user = userService.getById(id);

        UserDTO dto=new UserDTO();
        dto.setSex(user.getSex());
        dto.setAge(user.getAge());
        dto.setId(user.getId());
        dto.setName(user.getName());
        dto.setIdCard(user.getIdCard());
        dto.setVocation(user.getVocation());
        dto.setEthnic(user.getEthnic());
        dto.setPhone(user.getPhone());
        dto.setHomeAddress(user.getHomeAddress());
        dto.setGrade(user.getGrade());
        dto.setComAddress(user.getComAddress());
//        根据用户id获取所有技能特长id
        List<Long> specIds = rUserSpecialityService.findByUserId(id);

//        根据技能特长id查询技能名称和人物拥有这个技能详细情况
        List<SpecialityVO> specialityVOList = specialityService.findByIdsToUpdate(specIds,id);

        dto.setSpeciality(specialityVOList);

        //根据用户id获取所有证书id
        List<Long> cerIds = rUserCertifyService.findByUserId(id);

        //根据技能特长id查询技能名称和人物拥有这个技能详细情况
        List<CertifyDTO> certifyDTOList = certifyService.findByIdsToUpdate(cerIds, id);
        dto.setCertify(certifyDTOList);
     /*   String json = JSONUtil.toJsonStr(dto);
        redisTemplate.opsForValue().set(CACHE_CERTIFY_KEY+id,json);*/
        dto.setCertify(certifyDTOList);

        return R.success(dto);
    }


    @PostMapping("/forHelp")
    public R applyHelp(@RequestBody RescueInformation information){
//        System.out.println(information);
//        这里向管理员发送一个消息
        long phone = information.getPhone();

        Messages messages = new Messages();
        messages.setType(4);
        String msg = "居民需要您的帮助，联系电话:"+phone+"，该居民的地址为："
                +information.getPosition().getAddress()+information.getPosition().getName();
//        SMSUtils.sendMessage("曹涛的个人博客",msg,String.valueOf(phone),"1234");

        messages.setDescription(msg);
        messages.setTime(new Date());
        messages.setIdKey(phone);
        boolean save = messagesService.save(messages);
        if (!save){
            return R.error("呼叫失败，请重新尝试");
        }
//        将位置存储到缓存中，然后让管理员自己拿出来
//        redisTemplate.opsForValue().set(RedisConst.APPLY_POSITION,JSONUtil.toJsonStr(information));

        double longitude = information.getPosition().getLongitude();
        double latitude = information.getPosition().getLatitude();
        String addressName = information.getPosition().getName();
        redisTemplate.opsForGeo().add(RedisConst.POSITION+phone,new Point(longitude,latitude),addressName);
        return R.success();
    }

    @GetMapping("/homeLocation")
    public R getLocation(){
        String json = redisTemplate.opsForValue().get(RedisConst.APPLY_POSITION);
        RescueInformation information = JSONUtil.toBean(json, RescueInformation.class);
        Position position = information.getPosition();
        return R.success(position);
    }
    @GetMapping("/phoneList")
    public R phoneList(){
        String json = redisTemplate.opsForValue().get(RedisConst.PHONE_LIST);
        List<Phone> phones = JSONUtil.toList(json, Phone.class);
        return R.success(phones);
    }

}
